/**
 * @file     isCousins.js
 * @brief    [993. 二叉树的堂兄弟节点](https://leetcode.cn/problems/cousins-in-binary-tree/)
 * @author   Zhu
 * @date     2024-12-02 10:26
 */

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * DFS
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function (root, x, y) {
    let xx = undefined,
        yy = undefined;
    const stack = [[root, 1, null]];
    while (stack.length) {
        const [cur, depth, parent] = stack.pop();
        if (cur == null) continue;
        // handle node
        if (cur.val === x) xx = [depth, parent];
        if (cur.val === y) yy = [depth, parent];

        if (xx && yy) return xx[0] === yy[0] && xx[1] !== yy[1];

        stack.push([cur.right, depth + 1, cur], [cur.left, depth + 1, cur]);
    }

    return false;
};

/**
 * BFS
 * @param {TreeNode} root
 * @param {number} x
 * @param {number} y
 * @return {boolean}
 */
var isCousins = function (root, x, y) {
    let xx = undefined,
        yy = undefined;
    const queue = [[root, 1, null]];
    while (queue.length) {
        const [cur, depth, parent] = queue.shift();
        if (cur == null) continue;
        // handle node
        if (cur.val === x) xx = [depth, parent];
        if (cur.val === y) yy = [depth, parent];

        if (xx && yy) return xx[0] === yy[0] && xx[1] !== yy[1];

        queue.push([cur.left, depth + 1, cur], [cur.right, depth + 1, cur]);
    }

    return false;
};
